import {validateParameterRes} from "@/app/utils/validation";
import axios from "axios";
import {delay} from "framer-motion";
import useRequest from "@/app/utils/axiosRequest";

/**
 * 用户注册
 * @param setLoading
 * @param setSuccess
 * @param setError
 * @param setResData
 * @param isChecked
 * @param username
 * @param password
 * @param email
 * @constructor
 */
export default async function RegisterService({
                                                  setLoading,
                                                  setSuccess,
                                                  setError,
                                                  setResData,
                                                  isChecked,
                                                  username,
                                                  password,
                                                  email
                                              }: any) {
    setLoading(true);
    setSuccess(false);
    setError(false);
    setResData('');

    //axios统一配置中心
    const axiosInstance = useRequest();
    /*服务协议*/
    if (!isChecked) {
        setResData('请同意服务和隐私协议')
        setError(true);
        setLoading(false);
        return;
    }
    /*参数验证*/
    const [isValid, errorMessage] = validateParameterRes({username, password, email})
    if (!isValid) {
        setResData(errorMessage.toString());
        setError(true)
        setLoading(false)
        return false;
    }
    /*axios*/
    await axiosInstance.post('/user/user/register', {
        /*body*/
        username: username,
        password: password,
        email: email
    }, {
        headers: {
            'Content-Type': 'application/json'
        }
    }).then(response => {
        const data = response.data;
        if (data.status) {
            setResData(data.message);
            setSuccess(true);
            /*更换到登录页面 使用的PubSub-js框架*/
            PubSub.publish('username', username);
            PubSub.publish('password', password);
            /*延迟1秒*/
            /*（第1种)*/
            delay(v => {
                PubSub.publish('isLogin', true);/*发布消息*/
            }, 1000);
            /*
            /!*（第2中）*!/setTimeout(v => {
                PubSub.publish('isLogin', true);/!*发布消息*!/
            }, 1000);
            */
            return true;
        }
        setResData(data.message);
        setError(true);
        return false;
    }).catch(error => {
        setResData(error.message);
        setError(true);
        return false;
    }).finally(() => {
        /*更新Progress状态*/
        setLoading(false)
    })
}